﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Batman.Core;
using Batman.Jianbei.Forum.Core.Domains.Posts;
using Batman.Jianbei.Forum.Services.Posts.Dtos;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

namespace Batman.Jianbei.Forum.Services.Posts
{
    public class PostTintCollection : ApplicationService
    {
        public IRepository<PostTint, string> PostTintRepo { get; set; }

        /// <summary>
        /// 获取点赞统计
        /// </summary>
        /// <param name="postIds">帖子id列表</param>
        /// <param name="wxUIdWhoLike">一般是当前登录用户的微信用户表ID</param>
        /// <returns>{IsLike: 是否点赞, Count: 点赞总数, PostId: 帖子总数}</returns>
        public List<PostTintCount> GetTintCounts(List<string> postIds, string wxUIdWhoLike)
        {
            var query = PostTintRepo.GetAll().AsNoTracking().Where(t => postIds.Contains(t.PostId));

            List<PostTintCount> postLikeCounts = query.GroupBy(t => new { t.PostId, t.WxUserId }).Select(t => new PostTintCount
            {
                PostId = t.Key.PostId,
                LinkCount = t.Count(s => s.Type == PostTintType.Like),

                IsLike = t.ContainHisLike(wxUIdWhoLike),
                IsFavorite = t.ContainHisFavorite(wxUIdWhoLike)

            }).ToList();

            // todo: 缓存读取
            return postLikeCounts;
        }

        /// <summary>
        /// 收藏是否存在
        /// </summary>
        /// <param name="user"></param>
        /// <param name="postId"></param>
        /// <returns></returns>
        public bool HasHisFavorite(ClaimsPrincipal user, string postId)
        {
            bool exists = PostTintRepo.GetQuery().Where(t => t.Type == PostTintType.Favorite && t.PostId == postId).Any();
            return exists;
        }

        /// <summary>
        /// 添加收藏记录
        /// </summary>
        /// <param name="user"></param>
        /// <param name="postId"></param>
        public void AddHisFavorite(ClaimsPrincipal user, string postId)
        {
            bool exists = PostTintRepo.GetQuery().Where(t => t.Type == PostTintType.Favorite && t.PostId == postId).Any();
            if (exists) return;

            PostTintRepo.Insert(PostTint.NewFavorite(postId, user.GetWxUserId()));
        }

        /// <summary>
        /// 取消删除收藏
        /// </summary>
        /// <param name="user"></param>
        /// <param name="postId"></param>
        public void RemoveHisFavorite(ClaimsPrincipal user, string postId)
        {
            PostTintRepo.Delete(t => t.Type == PostTintType.Favorite && t.WxUserId == user.GetWxUserId());
        }
    }
}
